<?php

namespace App\Kuafu\User\Controller\B;

use App\Exceptions\CustomValidateException;
use App\Kuafu\Base\Controller\BaseController;
use App\Kuafu\Common\Enum\CodeEnum;
use App\Kuafu\Shop\Model\Shop;
use App\Kuafu\Sys\Enum\SysCacheEnum;
use App\Kuafu\User\Enum\RoleCodeEnum;
use App\Kuafu\User\Enum\UserCodeEnum;
use App\Kuafu\User\Exceptions\RoleException;
use App\Kuafu\User\Exceptions\UserException;
use App\Kuafu\User\Model\Role;
use App\Kuafu\User\Model\RolePermissionMappings;
use App\Kuafu\User\Model\UserRoleMapping;
use App\Kuafu\User\Service\PermissionsService;
use App\Kuafu\User\Service\RoleService;
use App\Kuafu\User\Validate\RoleV2Validate;
use App\Kuafu\User\Validate\RoleValidate;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

class RoleController extends BaseController
{
    /**
     * 新增(web)品牌角色
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function addBrandRole(Request $request)
    {
        $valid = RoleValidate::addRoleValidate($request->all());
        if ($valid) {
            return $this->fail(UserCodeEnum::ERR_PMS_NOT_INPUT, $valid);
        }

        $addRoleData = [
            'name'    => $request->post("name"),
            'brandId' => $request->header('brandId'),
            'type'    => RoleCodeEnum::ROLE_WEB_TYPE
        ];
        $roleId      = Role::addRole($addRoleData);

        // 权限关联存库
        RolePermissionMappings::batchCreateData($roleId, $request->permissionList);

        return $this->success();
    }

    /**
     * 新增(web)门店角色
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function addBrandShopRole(Request $request)
    {
        // TODO 新增(web)门店角色
        return $this->success();
    }

    /**
     * 新增(pos)门店角色
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function addShopRole(Request $request)
    {
        $valid = RoleValidate::addRoleValidate($request->all());
        if ($valid) {
            throw new RoleException(UserCodeEnum::ERR_PMS_NOT_INPUT, $valid);
        }

        $addRoleData = [
            'name'    => $request->post("name"),
            'brandId' => $request->header('brandId'),
            'type'    => RoleCodeEnum::ROLE_POS_TYPE
        ];
        $roleId      = Role::addRole($addRoleData);

        // 权限关联存库
        RolePermissionMappings::batchCreateData($roleId, $request->permissionList);

        return $this->success();
    }

    /**
     * 修改品牌角色
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function editRole(Request $request, int $roleId = 0)
    {
        $valid = RoleValidate::doRoleValidate($request->all() + ['roleId' => $roleId]);
        if ($valid) {
            return $this->fail(UserCodeEnum::ERR_PMS_NOT_INPUT, $valid);
        }

        $success = Role::editRole($request, $roleId);

        // 权限关联存库
        if ($success) {
            RolePermissionMappings::batchUpdateData($roleId, $request->permissionList);
        }

        Cache::forget(SysCacheEnum::getSysMenuList());

        return $this->success();
    }

    /**
     * 查询职位详情
     *
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     */
    public function getRoleInfo(Request $request, int $roleId = 0)
    {
        // 获取角色详情
        $res = RoleService::getRoleInfo($roleId);

        $platform = RoleService::switchTypeToPlatform($res['type']);

        $permission     = new PermissionsService($this->brandId, $this->shopId, $roleId, $platform);
        $permissionList = $permission->getPermissionsList();

        $data = [
            'roleInfo'       => $res,
            'permissionList' => $permissionList
        ];
        return $this->success($data);
    }

    /**
     * 查询所有角色(职位)列表 - 分页
     *
     * @param Request $request
     * @return JsonResponse
     * @throws CustomValidateException
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function getRoleList(Request $request): JsonResponse
    {

        $res = RoleService::getRoleList(
            $request->header('brandId'),
            $request->header('shopId'),
            (int)$request->get('pageSize', 20),
            (int)$request->get('pageNum', 1),
            RoleV2Validate::getRoleListValidate($request->all())
        );

        return $this->success($res);
    }

    /**
     * 查询 品牌/门店 角色(职位)列表
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function getRoleListById(Request $request, int $type = 0)
    {
        $result = [];
        if ($type == 1 || $type == 2 || $type == 3) {
            $result = Role::getAllRoleListByType($type);
        }
        return $this->success($result);
    }

    /**
     * 获取用户所有职位以及门店
     */
    public function getUserAllRole(Request $request)
    {
        $userId  = $request->userId;
        $brandId = $request->header('brandId');
        // 获取该用户所有的门店权限列表
        $roleList   = UserRoleMapping::query()->where('userId', $userId)->where('brandId', $brandId)->get();
        $returnData = [];
        if (!$roleList->isEmpty()) {
            $roleIdsList = $roleList->pluck('roleId');
            $shopIdList  = $roleList->pluck('shopId');
            $roleData    = Role::query()->whereIn('id', $roleIdsList)->where('type', 2)->get()->keyBy('id')->toArray();
            $shopData    = Shop::query()->whereIn('id', $shopIdList)->get()->keyBy('id')->toArray();


            $roleList = $roleList->toArray();

            foreach ($roleList as $roleKey => $role) {
                if (!key_exists($role['roleId'], $roleData) || !key_exists($role['shopId'], $shopData)) {
                    continue;
                }

                $returnData[] = [
                    'shopName' => $shopData[$role['shopId']]['name'],
                    'roleName' => $roleData[$role['roleId']]['name'],
                ];
            }
        }
        return $this->success($returnData);
    }

    /**
     * 删除某个角色
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function deleteRole(Request $request, int $roleId = 0)
    {
        if (RoleValidate::isInUsedRole($roleId)) {
            throw new RoleException(UserCodeEnum::ERR_PMS_ROLE_DELETE_IN_USED);
        };
        // 判断是否能删除
        RoleService::deleteRole($roleId);
        return $this->success();
    }

    /**
     * 新增(商家)门店角色
     * @param Request $request
     * @return JsonResponse
     * @throws RoleException
     * @throws UserException
     */
    public function addMerchantRole(Request $request)
    {
        $valid = RoleValidate::addRoleValidate($request->all());
        if ($valid) {
            throw new RoleException(UserCodeEnum::ERR_PMS_NOT_INPUT, $valid);
        }
        $addRoleData = [
            'name'    => $request->post("name"),
            'brandId' => $request->header('brandId'),
            'type'    => RoleCodeEnum::ROLE_BUSINESS_TYPE
        ];
        $roleId      = Role::addRole($addRoleData);
        // 权限关联存库
        RolePermissionMappings::batchCreateData($roleId, $request->permissionList);
        return $this->success();
    }

}
